﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace DCT.Huiteng.Utility
{
    public static class HttpExtUtility
    {
        public static HttpContext CurrentHttpContext
        {
            get { return HttpContext.Current; }
        }

        #region GetClientIP
        public static event Func<string> MockGetClientIPHandler;

        public static string GetClientIP(string specifyIpHeader)
        {
            if (MockGetClientIPHandler != null) {
                return MockGetClientIPHandler();
            }
            if (CurrentHttpContext != null)
            {
                string strIp = string.Empty;
                //先取Headers[specifyIpHeader"]，订制参数
                strIp = CurrentHttpContext.Request.Headers[specifyIpHeader];
                if (!string.IsNullOrEmpty(strIp))
                {
                    return strIp;
                }
            }
            return GetClientIP();
        }

        public static string GetClientIP()
        {
            if (MockGetClientIPHandler != null)
            {
                return MockGetClientIPHandler();
            }
            try
            {
                //得到用户ip
                if (CurrentHttpContext != null)
                {
                    string strIp = string.Empty;
                    strIp = CurrentHttpContext.Request.ServerVariables["REMOTE_ADDR"];
                    if (!string.IsNullOrEmpty(strIp))
                    {
                        return strIp;
                    }

                    strIp = CurrentHttpContext.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                    if (!string.IsNullOrEmpty(strIp))
                    {
                        return strIp;
                    }
                }
            }
            catch
            {
            }
            return "";
        } 
        #endregion

        public static string GetFullUrlPrefix() {
            return CurrentHttpContext.Request.Url.AbsoluteUri.Substring(0
                , CurrentHttpContext.Request.Url.AbsoluteUri.IndexOf(CurrentHttpContext.Request.Url.PathAndQuery));
        }
    }
}
